home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Compendium Deluxe 2
/
LSD and 17bit Compendium Deluxe - Volume II.iso
/
a
/
prog
/
asmsrc
/
thesource-7.lha
/
Source
/
polyfit.lha
/
polyfit
/
fit.c
next >
Wrap
C/C++ Source or Header
|
1990-05-04
|
3KB
|
159 lines
#include "fit.h"
static void ParseArgs();
static void Usage();
static void ReadPts();
static void PolyFit();
static void Results();
static void Stats();
static points Points;
static int MaxPt;
static int PtCnt;
static int Order;
static matrix Mat;
static double Det;
main(argc, argv)
int argc;
char **argv;
{
ParseArgs(argc, argv);
ReadPts();
if (PtCnt <= 0)
Usage();
PolyFit();
Results();
Stats();
}
static void ParseArgs(argc, argv)
int argc;
char **argv;
{
if (argc != 3)
Usage(argv[0]);
MaxPt = atoi(argv[1]);
Order = atoi(argv[2]);
if (MaxPt <= 0 || Order <= 0)
Usage(argv[0]);
}
static void Usage(prog)
char *prog;
{
fprintf(stderr,
"Usage: %s max-number-of-data-points order-of-polynomial\n", prog);
fprintf(stderr,
"Note: points are read from stdin (a coordinate point/line)\n");
exit(1);
}
static void ReadPts()
{
char line[1024];
Points = (points)Calloc(MaxPt, sizeof(point));
for (PtCnt = 0; PtCnt < MaxPt; PtCnt++)
{
if (gets(line) == NULL)
return;
sscanf(line, "%f %f", &Points[PtCnt].X, &Points[PtCnt].Y);
}
}
static void PolyFit()
{
register int i, p, r, c;
register matrow xvec;
Mat = MatInit(Order + 1);
xvec = (matrow)Calloc(Order * 2 + 1, sizeof(matelm));
for (p = 0; p < PtCnt; p++)
{
for (xvec[0] = 1.0, i = 1; i <= Order * 2; i++)
xvec[i] = xvec[i - 1] * Points[p].X;
for (r = 0; r < Order + 1; r++)
{
Mat[r][Order + 1] += Points[p].Y * xvec[r];
for (c = 0; c < Order + 1; c++)
Mat[r][c] += xvec[r + c];
}
}
Det = MatInv(Order + 1, Mat);
}
static void Results()
{
register int i;
printf("%5d = Number of data points input\n", PtCnt);
printf("%5d = Order of polynomial fit\n\n", Order);
#ifndef NO_DETERM
printf("%e = Determinate of matrix solution\n\n", Det);
#endif
printf("y = %f", Mat[0][Order + 1]);
for (i = 1; i < Order + 1; i++)
printf(" + %f x^%d", Mat[i][Order + 1], i);
}
static void Stats()
{
register int i, j;
double x, y;
double sum, sum2, minerr, maxerr;
sum = sum2 = maxerr = 0;
minerr = HUGE;
for (i = 0; i < PtCnt; i++)
{
y = Mat[0][Order + 1];
for (x = 1, j = 1; j < Order + 1; j++)
{
x *= Points[i].X;
y += x * Mat[j][Order + 1];
}
y -= Points[i].Y;
if (y < 0)
y = -y;
sum += y;
sum2 += y * y;
if (y < minerr)
minerr = y;
if (y > maxerr)
maxerr = y;
}
printf("\n\nFit statistics:\n");
printf("%30.15f = Standard Error of Estimate\n", sqrt(sum2 / (PtCnt - 2)));
printf("%30.15f = Average Error\n", sum / PtCnt);
printf("%30.15f = Error's Standard Deviation\n",
sqrt((PtCnt * sum2 - sum * sum) / PtCnt / (PtCnt - 1)));
printf("%30.15f = Minimum Error\n", minerr);
printf("%30.15f = Maximum Error\n", maxerr);
}